package xyz.hlh.boot3.exception;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HLH
 * @description 简单的异常处理，相应json字符串
 * @email 17703595860@163.com
 * @date Created in 2021/8/7 上午10:47
 */
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 第一种方式，直接通过response返回相应信息
        /*response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map =  new HashMap<String, Object>() {{
            put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            put("errorMsg", (ex instanceof MyException) ? ex.getMessage() : "系统错误");
        }};
        writer.print(JSONUtil.toJsonStr(map));
        writer.flush();
        writer.close();*/
        // 第二种方式，通过设置MappingJackson2JsonView视图，返回json格式
        ModelAndView modelAndView = new ModelAndView();
        MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
        modelAndView.setView(mappingJackson2JsonView);
        modelAndView.addObject("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        modelAndView.addObject("errorMsg", (ex instanceof MyException) ? ex.getMessage() : "系统错误");
        return modelAndView;
    }
}
